<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item>
        <el-select
clearable v-model="queryParams.siteId" @change="getChannelTree()" 
        class="!w-240px">
          <el-option
            v-for="item in siteDatas"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          /> </el-select
      ></el-form-item>
      <el-form-item>
        <el-tree-select
          clearable
          ref="treeRef"
          v-model="queryParams.channelId"
          :data="treeOptions"
          :props="defaultProps"
          node-key="id"
          :render-after-expand="false"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="关键词" prop="q">
        <el-input
          v-model="queryParams.q"
          class="!w-240px"
          clearable
          placeholder="请输入关键词"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetIndex" type="primary">
          <Icon class="mr-5px" icon="ep:refresh" />
          重新生成索引
        </el-button>
        <el-button @click="submitBatch('offline')" type="danger">
          <Icon class="mr-5px" icon="ep:arrow-down-bold" />
          下线
        </el-button>
        <el-button @click="submitBatch('delete')" type="danger">
          <Icon class="mr-5px" icon="ep:delete" />
          删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      ref="tableRef"
      row-key="id"
      @selection-change="handleDataSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column align="center" label="ID" prop="id" />
      <el-table-column
        align="center"
        label="标题"
        prop="title"
        width="600px"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="站点" prop="siteName" />
      <el-table-column align="center" label="栏目" prop="channelName" />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="发布时间"
        prop="releaseTime"
        width="180"
      />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="索引时间"
        prop="indexTime"
        width="180"
      />
      <el-table-column :width="300" align="center" label="操作">
        <template #default="scope">
          <el-button link class="el-link-button">
            <el-link link type="primary" target="_blank" :href="scope.row.url"> 浏览 </el-link>
          </el-button>
          <el-button link type="danger" @click="handleOffline(scope.row.id)"> 下线 </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
</template>
<script setup lang="ts" name="ContentEsIndex">
// 全局相关的 import
import { ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { dateFormatter } from '@/utils/formatTime'
import * as ContentApi from '@/api/cms/content'
import * as SiteApi from '@/api/cms/site'
import * as ChannelApi from '@/api/cms/channel'
import { ElTree } from 'element-plus'
import { defaultProps, handleTree } from '@/utils/tree'
import { ContentSelectPageVO } from '@/api/cms/content/types'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const siteDatas = ref() //站点列表
const treeOptions = ref<any[]>([]) // 栏目树形结构
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  q: '',
  siteId: undefined,
  channelId: undefined
})
const treeRef = ref<InstanceType<typeof ElTree>>()
const queryFormRef = ref() // 搜索的表单
const tableRef = ref() // 表格的 Ref

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ContentApi.getContentIndexPageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重新生成索引按钮操作 */
const resetIndex = async () => {
  try {
    // 重新生成的二次确认
    await message.delConfirm(t('cms.content.confirm.resetIndex'))
    // 发起重新生成
    await ContentApi.resetContentIndexApi(queryParams)
    message.success(t('common.success'))
    // 刷新列表
    await getList()
  } catch {}
}

const contentIds = ref<number[]>([]) // 表格的选中 ID 数组
/** 当内容主操作表格选择项发生变化时会触发该事件  */
const handleDataSelectionChange = (array: ContentSelectPageVO[]) => {
  contentIds.value = []
  if (!array) {
    return
  }
  array.forEach((row) => contentIds.value.push(row.id))
}

//执行批量内容操作
const submitBatch = async (action: string) => {
  if (contentIds.value.length === 0) {
    return
  }
  await handleBatchExecute(action, contentIds.value)
}

const handleBatchExecute = async (action: string, ids: number[]) => {
  //动作 删除 提交审核 下线 归档
  if (action === 'delete') {
    // 删除的二次确认
    await message.delConfirm()
    await ContentApi.deleteContentApi(ids)
    tableRef.value.clearSelection()
    handleQuery()
  } else if (action === 'offline') {
    // 下线的二次确认
    await message.delConfirm(t('cms.content.confirm.offline'))
    await ContentApi.offlineContentApi(ids)
    tableRef.value.clearSelection()
    handleQuery()
  } else {
    throw new Error(`not support action: ${action}`)
  }
}
/** 下线按钮操作 */
const handleOffline = async (id: number) => {
  try {
    // 下线的二次确认
    await message.delConfirm(t('cms.content.confirm.offline'))
    // 发起下线
    await ContentApi.offlineContentApi([id])
    message.success(t('common.success'))
    // 刷新列表
    await getList()
  } catch {}
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ContentApi.deleteContentApi([id])
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
const getChannelTree = async () => {
  const channels = await ChannelApi.listSimpleChannelApi(queryParams.siteId)
  treeOptions.value = []
  treeOptions.value = handleTree(channels)
}
/** 初始化 **/
onMounted(async () => {
  getList()
  siteDatas.value = await SiteApi.listSimpleSiteApi()
})
</script>
